package luit.mmt02.activity;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import luit.mmt02.R;
import luit.mmt02.adapter.myadapter;
import luit.mmt02.dataAccess.db_email;
import luit.mmt02.doituong.OneMail;
import luit.mmt02.doituong.showToast;
import luit.mmt02.mailControl.MdeamonControl;
import luit.mmt02.xuly.ConvertMessageToList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class getNoiboActivity extends Activity // hien thi mail tren 1 list
{
	final static String tag   = "getNoiboActivity";
	MdeamonControl g ;
	
	//---------------------------------Copy...
	final static String KEY_ARRAY_TO_NEWMAIL = "KeyArrToNewMail";
	final static String LOAI_SEND = "LOAISEND";
	final static String NEWMAIL = "NEWMAIL";
	final static String REPLY = "REPLY";
	final static String FORWARD = "FORWARD";
	final static String KEY_USERNAME_LOGIN = "USERNAMELOGIN"; // nhan USERVA PASS tu showmail activity gui toi de login
	final static String KEY_PASSWORD_LOGIN = "PASSWORDLOGIN";
	static final String FROM = "from";
	static final String BODY = "body";
	static final String SUB = "sub";
	static final String DATE = "date";
	static final String TIME = "time";
	static final String TO = "to";
	//option......................
	static final String ATTACH = "attach";
	static final String VOICE = "voice";
	static final String ENCRYPT = "encrypt";
	String username;
	String password;
	ArrayAdapter<OneMail>adapter;
	Message[]message;
	showToast d;
	List<OneMail>list; //list truyen vao adapter
	int n ; // so mail
	Bundle bundle; //nhan username va password
	ListView listview; //lay listview
	View view; // view footer
	LayoutInflater Linflater;
	Button btn_more, btn_logout;
	
	//
	
	db_email mydb;
	Cursor mCursor;
	int i_start_query_more = 6;
	boolean flag_getmessage = false;
	Intent intent;
	String []value;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_email_login);
		listview = (ListView)findViewById(R.id.listview_list_email);
		d = new showToast(getBaseContext());
		list = new ArrayList<OneMail>();	
		//
		Linflater = getLayoutInflater();
		view = Linflater.inflate(R.layout.footer_list_mail, null);
		//
		bundle = getIntent().getExtras();
		username = bundle.getString(KEY_USERNAME_LOGIN);
		password = bundle.getString(KEY_PASSWORD_LOGIN);
//		Log.v(tag, "Nhan duoc : " + username + " | " + password);
		//goi class loadmail chay nhu 1 tien trinh moi
		new load_noibo_async().execute(tag);
		//-------------
		btn_more = (Button)view.findViewById(R.id.btn_foot_more);
		
		btn_more.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				d.showmess(getResources().getString(R.string.addmore) + " . . .");
				add_more_mail_to_list();
//				new load_more_mail().execute(null);
			}
		});
		
		btn_logout = (Button)view.findViewById(R.id.btn_foot_logout); // tro ve man hinh chon email
		btn_logout.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO REMOVE USERNAME NAY RA KHOI CSDL
				startActivity(new Intent(getNoiboActivity.this, ListMailActivity.class));
			}
		});
		
		TextView txt_email = (TextView)view.findViewById(R.id.txt_foot_email);
		txt_email.setText(username);
		
		
	}
	
	// asyncTask Load mail
		private class load_noibo_async extends AsyncTask<String,String	, Message[]>
		{
			ProgressDialog pdialog = new ProgressDialog(getNoiboActivity.this);
			
			@Override
			protected void onPreExecute() 
			{
//				pdialog.setTitle("Get Mail");
				String str = getResources().getString(R.string.connect_noibo);
				pdialog.setMessage(str + " \n" +username);
				pdialog.show();
				super.onPreExecute();
			}

			@Override
			protected Message[] doInBackground(String... params) 
			{
				// TODO Auto-generated method stub
				doinbackGround();
				return null;
				
			}
			@Override
			protected void onPostExecute(Message[] resultMes) {
				// TODO Auto-generated method stub
				Log.v(tag,"on post");
				listview.addFooterView(view);
				listview.setAdapter(adapter);
				pdialog.dismiss();
				super.onPostExecute(resultMes);
			}
			
		}
		
		//tao 1 tien trinh load them email rieng, 1 dialog bao ng dung doi
		@SuppressWarnings("unused")
		private class load_more_mail extends AsyncTask<String, String, String>
		{
			ProgressDialog pdialog = new ProgressDialog(getNoiboActivity.this);
			
			@Override
			protected void onPreExecute() 
			{
//				pdialog.setTitle("Get Mail");
				pdialog.setMessage("Loading ...");
				pdialog.show();
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				add_more_mail_to_list();
			// lay 5 mail tu csdl cho vao list
				
				return null;
			}
			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
//				adapter.notifyDataSetChanged();
				pdialog.dismiss();
				super.onPostExecute(result);
				
			}
			
		}
		
		public void doinbackGround()
		{
			// kiem tra CSDL cua user
			try
			{
				flag_getmessage = false;
			Log.v(tag, "doinBackGroud");
			g = new MdeamonControl(username, password);
			String []str = username.split("@");
			String db_name = "db_" + str[0] +"_noibo";
			Log.v(tag,"db_name: " + db_name);
			mydb = new db_email(this, db_name);
			mydb.open();
			mCursor = mydb.query(1,5);
			int i_tongmail = mCursor.getCount();
			Log.v(tag, "GGGGGGGGGG TONGMAIL: " + i_tongmail + " ---");
			if(i_tongmail == 0)
			{
				Log.v(tag, "CSDL trong, load mail tu server ...");
				mCursor.close();
				message = g.getmail();
				flag_getmessage = true;
				mydb.save_msg_to_db(message);
				Log.v(tag, "save mail vao csdl tai khoan " + username);
				int length_mess = message.length;
				if(length_mess < 5)
					mCursor = mydb.query(1,length_mess);
				else
					mCursor = mydb.query(1,5);
			}
			else
				Log.v(tag, "Da co csdl, load csdl sqlite");
			Log.v(tag, "SO ROW save: " + mCursor.getCount());
			if(mCursor.moveToFirst()) // neu co csdk , dua 5 mail vao list,adapter
			{
				do
				{
					int id = mCursor.getInt(0);
					String from = mCursor.getString(1);
					String to = mCursor.getString(2);
					String sub = mCursor.getString(3);
					String body = mCursor.getString(4);
					String time = mCursor.getString(5);
					int flag_attach = mCursor.getInt(6);
					int flag_favorite = mCursor.getInt(7);
					int flag_encrypt = mCursor.getInt(8);
					int flag_voice = mCursor.getInt(9);
					int flag_read = mCursor.getInt(10);
					String str_attach = mCursor.getString(11);
					boolean f_att = (flag_attach == 1 ? true:false);
					boolean f_fa = (flag_favorite == 1 ? true:false);
					boolean f_en = (flag_encrypt ==1 ? true:false);
					boolean f_voi = (flag_voice==1?true:false);
					boolean f_read = (flag_read == 1 ? true:false);
					OneMail om3 = new OneMail(id, from, to, 
							sub, body, time, f_att, f_fa, f_en, f_voi, f_read, str_attach);
					list.add(om3);
					
				}while (mCursor.moveToNext());
			}
			
//			
			Log.v(tag, "check message");
//			if(flag_getmessage == false)//va kiem tra co ket noi mang
//			{
//				Log.v(tag, "getmail ...");
//				message = g.getmail();
////				message = null;
//			}
//			else
//				d.showmess("khong co ket noi mang ...");
			message = null;
			adapter = new myadapter(this, list, message,db_name,username); //mes truyen vao adapter thuc hien update favorite
			mCursor.close();
			mydb.close();
			}catch (Exception e) {
				// TODO: handle exception
				Log.e(tag, "loi do in back" + e.toString());
			}
			finally
			{
				mCursor.close();
				mydb.close();
				
			}
		}
		
		public void add_more_mail_to_list()
		{
			mydb.open();
			//duyet tu mail thu 6 , den mail 10, sau moi lan duyet , mail bat dau duyet se dc + 5;
			mCursor = mydb.query(i_start_query_more, i_start_query_more +4);
			Log.v(tag, "ADD_more_mail");
			//
			if(mCursor.moveToFirst() && mCursor.getCount() >= 1)
			{
				do
				{
					int id = mCursor.getInt(0);
					String from = mCursor.getString(1);
					String to = mCursor.getString(2);
					String sub = mCursor.getString(3);
					String body = mCursor.getString(4);
					String time = mCursor.getString(5);
					int flag_attach = mCursor.getInt(6);
					int flag_favorite = mCursor.getInt(7);
					int flag_encrypt = mCursor.getInt(8);
					int flag_voice = mCursor.getInt(9);
					int flag_read = mCursor.getInt(10);
					String str_attach = mCursor.getString(11);
					boolean f_att = (flag_attach == 1 ? true:false);
					boolean f_fa = (flag_favorite == 1 ? true:false);
					boolean f_en = (flag_encrypt ==1 ? true:false);
					boolean f_voi = (flag_voice==1?true:false);
					boolean f_read = (flag_read == 1 ? true:false);
					OneMail om3 = new OneMail(id, from, to, 
							sub, body, time, f_att, f_fa, f_en, f_voi, f_read, str_attach);
					list.add(om3);
//					adapter.add(om3);
					
				}while (mCursor.moveToNext());
			}else
			{
				d.showmess("Loading...");
			}
			
			i_start_query_more += 5;
			mCursor.close();
			mydb.close();
			adapter.notifyDataSetChanged();
			
		}
		
		//
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// TODO Auto-generated method stub
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.layout_menu, menu);
			return super.onCreateOptionsMenu(menu);
		}
		//khi click vao menu item
		@Override
		public boolean onOptionsItemSelected(MenuItem item) 
		{
			// TODO Auto-generated method stub
			switch (item.getItemId()) 
			{
			case R.id.item_layout_refresh:
				d.showmess("refresh");
				refresh();
				break;
			case R.id.item_layout_compose:
				value = new String[10];
				value[0] = username;
				value[1] = password;
				value[2] = NEWMAIL;
				intent = new Intent(this,newmailActivity.class);
				intent.putExtra(KEY_ARRAY_TO_NEWMAIL, value);
				startActivity(intent);
				break;
			case R.id.item_layout_search:
				d.showmess("serach");
				break;
//			case R.id.item_layout_markAll:
//				mark_all();
//				break;
//			case R.id.item_layout_unMark:
//				unmark_all();
//				break;
//			case R.id.item_layout_delete:
//				Alert_yes_no_delete();
//				break;
			default:
				break;
			}
			return super.onOptionsItemSelected(item);
		}
		
		public void refresh()
		{
			try
			{
				Log.v(tag, "Tien hanh refresh ...update CSDL...");
				mydb.open();
				mydb.removeALl();
				mydb.close();
				list.removeAll(list);
				new load_noibo_async().execute("refresh");
				adapter.notifyDataSetChanged();
			}catch (Exception e) {
				// TODO: handle exception
				Log.v(tag, "khong the refresh");
			}
		}
		
		public void mark_all()
		{
			int i_list = list.size();
			for(int i = 0 ; i < i_list; i ++)
			{
				list.get(i).setCheck(true);
			}
			adapter.notifyDataSetChanged();
		}
		public void unmark_all()
		{
			int i_list = list.size();
			for(int i = 0 ; i < i_list; i ++)
			{
				list.get(i).setCheck(false);
			}
			adapter.notifyDataSetChanged();
		}
		
		public void delete_mess()
		{
			int i_list = list.size();
			ConvertMessageToList cv = new ConvertMessageToList();
			mydb.open();
			List<Integer>i_del = new ArrayList<Integer>();
			
			for(int i = 0 ; i < i_list; i ++)
			{
				OneMail o3 = list.get(i);
				if(o3.isCheck()) // neu dc check
				{
					Log.v(tag, "Tien hanh delete..." + i);
					cv.delete_message(message, message.length - i - 1);
					mydb.remove_by_stt(i+1);
					i_del.add(i);
				}
			}
			for(int i : i_del)
			{
				list.remove(i);
			}
			mydb.close();
			adapter.notifyDataSetChanged();
		}
		
		public void Alert_yes_no_delete()
		{
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setMessage(getResources().getString(R.string.alert_yes_no));
			alert.setPositiveButton("OK", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					delete_mess();
				}
			});
			alert.setNegativeButton("Cancel", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			});
			AlertDialog al_dialog = alert.create();
			al_dialog.setIcon(R.drawable.err_happy_5);
			al_dialog.show();
		}
}
